package com.yonghui.summer.code.dao.handler;

import com.yonghui.summer.code.dao.utils.ParamValueBuilder;
import com.yonghui.summer.code.dao.utils.ProcessorHelper;
import com.yonghui.summer.code.dao.utils.SqlBuilderHelper;
import com.yonghui.summer.po.MybatisParam;
import com.yonghui.summer.po.TableMapping;
import lombok.AllArgsConstructor;
import lombok.Data;

import javax.annotation.processing.Messager;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;

/**
 * @auther yangchuan
 * @date 2021-03-27 14:32
 */
@Data
@AllArgsConstructor
public class MybatisProviderParamsHandler {

    private Messager messager;
    private Elements elementUtils;

    public TableMapping getTableMapping(String className) {
        TableMapping tableMapping = null;
        try {
            Class clazz = Class.forName(className);
            tableMapping = SqlBuilderHelper.getTableMappingCache(clazz);
        } catch (ClassNotFoundException e1) {
            TypeElement typeElement = getElementUtils().getTypeElement(className);
            tableMapping = SqlBuilderHelper.getTableMappingCache(typeElement);
        }
        return tableMapping;
    }

    public String generateParamValue(VariableElement ve) {
        StringBuilder sb = new StringBuilder();
        String arg = ve.getSimpleName().toString();
        MybatisParam mybatisParam = ProcessorHelper.getParam(ve, arg);
        ParamValueBuilder pvb = ParamValueBuilder.builder().setMybatisParam(mybatisParam);
        String paramType = ve.asType().toString();
        if (paramType.startsWith("java")) {
            return pvb.build();
        } else {
            TableMapping tableMapping = getTableMapping(paramType);
            return pvb.setTableMapping(tableMapping).build();
        }
    }
}
